package com.yonyou.pmclouds.plan.utils;
import com.yonyou.pmclouds.basecom.exception.BusinessException;
import com.yonyou.pmclouds.plan.utils.compare.Assembly;
import com.yonyou.pmclouds.plan.utils.compare.PlanVersion;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.Unmarshaller;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;

public class CompareConfigurationUtil {

    public static PlanVersion getConfInfo() throws BusinessException {

        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(new ClassPathResource("planversion-compare.xml").getInputStream()));
            StringBuffer buffer = new StringBuffer();
            String data = null;

            while((data = br.readLine()) != null) {
                buffer.append(data);
            }

            br.close();

            if(StringUtils.isNotEmpty(buffer.toString())){

                //转换后得到xml对应的javabean
                Assembly assembly = null;
                try {
                    assembly = convertToJavaBean(buffer.toString(), Assembly.class);
                } catch (BusinessException e) {
                    throw new BusinessException("配置文件读取错误");
                }
                //根据单据类型的判断取到最终需要的配置文件属性
                return assembly.getPlanVersion();
            }else{
                throw new BusinessException("配置文件读取错误");
            }
        } catch (IOException e) {
            throw new BusinessException("配置文件读取错误");
        }
    }

    public static <T> T convertToJavaBean(String xml, Class<T> c) throws BusinessException{
        if (StringUtils.isEmpty(xml)){
            return null;
        }
        T t = null;
        try{
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        }catch(Exception e){
            throw new BusinessException("配置文件读取错误");
        }
        return t;
    }
}
